package com.csair.seam.infrastructure.utils;

import java.security.MessageDigest;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

/**
 * @Author: wurunbin
 * @Date: 2020/3/5 15:02
 * @Description:
 **/
public class AESHelper {

    private static final String ENCODE = "UTF-8"; // AES加密时使用UTF8编码方式

    /**
     *
     * @param encryptedString
     *            密文
     * @param key
     *            密码
     * @return
     * @throws Exception
     */
    public static String aesDecrypt(String encryptedString, String key)
            throws Exception {
        byte[] keyArray = shortMD5(key);
        SecretKeySpec skeySpec = new SecretKeySpec(keyArray, "AES");
        
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//NOSONAR
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        byte[] encryptedData = Base64.decodeBase64(encryptedString
                .getBytes(ENCODE));
        byte[] original = cipher.doFinal(encryptedData);
        return new String(original, ENCODE);
    }

    /**
     *
     * @param data 需加密明文数据
     * @param key 加密密码
     * @return
     * @throws Exception
     */
    public static String aesEncrypt(String data, String key) throws Exception {
        byte[] plainBytes = data.getBytes(ENCODE);
        byte[] keyBytes = shortMD5(key);
        SecretKeySpec skeySpec = new SecretKeySpec(keyBytes, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//NOSONAR
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(plainBytes);
        return new String(Base64.encodeBase64(encrypted), ENCODE);
    }

    @SuppressWarnings("all")
    private static byte[] shortMD5(String b) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(b.getBytes(ENCODE));
        return md.digest();
    }
}